package org.example;

import bean.DB;
import bean.ResponseUtils;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
@WebServlet("/deleteOrderServlet")
public class deleteOrderServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取订单ID
        String orderIdStr = request.getParameter("orderId");
        if (orderIdStr == null || orderIdStr.isEmpty()) {
            // 如果订单ID为空，使用 ResponseUtils 发送错误信息并重定向
            ResponseUtils.sendResponse(response, "订单ID无效", "orderPage.jsp?error=订单ID无效");
            return;
        }

        // 将订单ID转换为整数
        int orderId = Integer.parseInt(orderIdStr);

        // 创建数据库连接
        DB db = new DB();
        String deleteQuery = "DELETE FROM userorders WHERE order_id = ?";

        try (Connection conn = db.createConn(); PreparedStatement pstmt = conn.prepareStatement(deleteQuery)) {
            // 设置查询参数
            pstmt.setInt(1, orderId);

            // 执行删除操作
            int rowsAffected = pstmt.executeUpdate();
            if (rowsAffected > 0) {
                ResponseUtils.sendResponse(response, "订单删除成功", "orderPage.jsp?success=订单删除成功");
            } else {
                ResponseUtils.sendResponse(response, "订单删除失败", "orderPage.jsp?error=订单删除失败");
            }
        } catch (SQLException e) {
            e.printStackTrace();
            ResponseUtils.sendResponse(response, "数据库错误，请稍后重试", "orderPage.jsp?error=数据库错误，请稍后重试");
        }
    }
}
